<template>
  <div>
    <el-dialog v-model="visible" :title="formData.form.title" :close-on-click-modal="false"
      :close-on-press-escape="false" @close="closeDialog" width="618">
      <el-form ref="formRef" :rules="rules" :model="formData.form">
        <el-form-item required label="网格名称" label-width="85px" prop="name"
          style="width: 320px; padding-top: 20px; margin-left: 52px">
          <el-input v-model="formData.form.name" />
        </el-form-item>
        <el-form-item required label="网格类型" prop="category" style="width: 320px; padding-top: 10px; margin-left: 52px">
          <el-select v-model="formData.form.category" placeholder="" placement="bottom">
            <el-option v-for="item in optiontype" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="上级组织" prop="parentId" label-width="85px"
          style="width: 320px; padding-top: 10px; margin-left: 52px">
          <el-tree-select filterable v-model="formData.form.parentId" check-strictly placeholder="" :data="optionarea"
            default-expand-all />
          <div style="font-size: 12px; color: #999999">上级组织为空默认根组织</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog" class="btnhover" style="
              width: 80px;
              height: 30px;
              background-color: rgba(255, 255, 255, 1);
              border: 1px solid rgba(187, 187, 187, 1);
              color: rgba(142, 142, 142, 1);
            ">取消</el-button>
          <el-button @click="besurebtn" class="btnhover" style="
              width: 80px;
              height: 30px;
              background-color: #ff9900;
              border: 1px solid #ff9900;
              color: rgba(255, 255, 255, 1);
            ">
            确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import * as getgridApi from '@/api/countryside/gridmanagement/index'
import globalApi from '@/api/spb/global'
const formRef = ref() // 表单 Ref
const formData = reactive({
  form: {
    name: '',
    category: '',
    parentId: '',
    title: ''
  }
})
const rules = reactive({
  name: [{ required: true, message: '网格名称不能为空！', trigger: 'change' }],
  category: [{ required: true, message: '网格类型不能为空！', trigger: 'change' }]
})
const props = defineProps({
  visible: Boolean,
  editData: {
    type: Object
  }
})
const emit = defineEmits(['update:visible', 'geteditData'])
const visible = computed({
  get: () => {
    return props.visible
  },
  set: (val) => emit('update:visible', val)
})
const optiontype = ref([])
watch(
  () => props.editData,
  (val) => {
    if (val) {
      formData.form.name = val.gridName
      formData.form.category = val.category
      formData.form.parentId = val.parentId
      formData.form.title = val.dialogtitle
    }
  },
  { immediate: true }
)
watch(
  () => props.visible,
  (val) => {
    if (val == true) {
      getTypeData()
      getAreaOrganization()
    }
  },
  { immediate: true }
)
/** 获取类型列表 */
const getTypeData = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_grid_area_type'
  }
  globalApi.getDictData(params).then((res) => {
    optiontype.value = res.list
  })
}
//处理树形数据加value和label
function traverse(nodes) {
  nodes.forEach((node) => {
    if (node.id) {
      node.label = node.gridName
      node.value = node.id
    }
    if (node.gridName === formData.form.name) {
      node.disabled = true
    }
    if (node.children && Array.isArray(node.children)) {
      traverse(node.children)
    }
  })
}
// 获取网格管理列表
const optionarea = ref([])
function getAreaOrganization() {
  optionarea.value = []
  getgridApi.getGridList().then((res) => {
    let cloneData = JSON.parse(JSON.stringify(res)) // 对源数据深度克隆
    cloneData = cloneData.filter((father) => {
      // 循环所有项，并添加children属性
      let branchArr = cloneData.filter((child) => father.id == child.parentId) // 返回每一项的子级数组
      branchArr.length > 0 ? (father.children = branchArr) : '' //给父级添加一个children属性，并赋值
      return father.parentId == 0 //返回第一层
    })
    traverse(cloneData)
    if (cloneData.length === 0) {
      optionarea.value = res
    } else {
      optionarea.value = cloneData
    }
  })
}
/** 取消 */
const closeDialog = () => {
  visible.value = false
  emit('geteditData', props.editData.pageNo)
}
/** 确定 */
const besurebtn = async () => {
  await formRef.value.validate()
  const GridData = {
    gridName: formData.form.name,
    category: formData.form.category,
    parentId: formData.form.parentId
  }
  if (formData.form.title === '新增网格') {
    ElMessageBox.confirm('是否确认新增网格?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        if (!formData.form.parentId) {
          GridData.parentId = 0
        }
        getgridApi.createGrid(GridData).then((res) => {
          if (res) {
            ElMessage.success('新增成功！')
            emit('geteditData', props.editData.pageNo)
            visible.value = false
          }
        })
      })
      .catch(() => {
        ElMessage.info('已取消新增网格')
      })
  }
  if (formData.form.title === '编辑网格') {
    ElMessageBox.confirm('是否确认编辑网格?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        GridData.id = props.editData.id
        getgridApi.updateGrid(GridData).then((res) => {
          if (res) {
            ElMessage.success('修改成功！')
            emit('geteditData', props.editData.pageNo)
            visible.value = false
          }
        })
      })
      .catch(() => {
        ElMessage.info('已取消编辑网格')
      })
  }
}

onMounted(() => { })
</script>
<style scoped>
::v-deep .el-dialog__body {
  padding: 0 0 10px 0 !important;
}

.btnhover:hover {
  opacity: 0.8;
}
</style>